package com.peter.dbcp_demon;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		try {
			Connection conn = DBUtils.getConnection();
			Statement sta = conn.createStatement();

			ResultSet rs = sta.executeQuery("select * from test01");

			while (rs.next()) {

				System.out.println(rs.getString(1) + "     " + rs.getString(2));
			}

//			System.out.println(conn.isClosed());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class B {
	public static void main(String[] args) throws FileNotFoundException {
		try {

			File file = new File("db.properties");
			InputStream inputStream = new FileInputStream(file);
//			InputStream inputStream = B.class.getClassLoader().getResourceAsStream("db.properties");

			Properties properties = new Properties();
			properties.load(inputStream);

			System.out.println(properties.getProperty("url"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class DBUtils {

	private static Properties properties = new Properties();

	private static BasicDataSource bds;

	static {
//		if (bds == null) {
//			bds = new BasicDataSource();
//		}

		InputStream is = null;
		try {
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
			properties.load(is);
			// 分别设置数据库的连接参数
//			bds.setDriverClassName(properties.getProperty("driverName"));
//			bds.setUrl(properties.getProperty("url"));
//			bds.setUsername(properties.getProperty("user"));
//			bds.setPassword(properties.getProperty("password"));

			if (bds == null) {
				bds = BasicDataSourceFactory.createDataSource(properties);
			}

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static Connection getConnection() throws SQLException {
		return bds.getConnection();
	}
}
